import { InboxOutlined } from '@ant-design/icons';
import { Modal, notification, Upload } from 'antd';
import Dragger from 'antd/es/upload/Dragger';
import React from 'react';
import { uploadUsingPost } from '@/services/backend/fileInfoController';

interface Props {
  modalVisible: boolean;
  onCancel: () => void;
  onSubmit: (val: string) => void;
}

const UploadModal: React.FC<Props> = (props) => {
  const { modalVisible, onCancel, onSubmit } = props;
  return (
    <Modal
      title={'上传'}
      open={modalVisible}
      destroyOnClose
      onCancel={onCancel}
      footer={null}
    >
      <Dragger
        style={{ margin: '20px 0' }}
        name={'file'}
        multiple={false}
        maxCount={1}
        customRequest={async (options) => {
          const file = options.file as File;
          try {
            //1. 文件上传
            const res = await  uploadUsingPost({},file)
            if (res.code === 0) {
              notification.success({
                message: '文件上传成功',
                description: `${options.filename}文件上传成功`,
              });
            }
            //2. 将url传递给父组件
            onSubmit(res?.data ?? '');
          } catch (e: any) {
            notification.error({
              message: '文件上传失败',
              description: e.message,
            });
          }
        }}
        beforeUpload={(file) => {
          const isSize = file.size / (1024 * 1024) < 10;
          if (!isSize) {
            notification.error({
              message: '文件大小不符',
              description: '仅支持文件大小10MB',
            });
            return Upload.LIST_IGNORE;
          }
          return true;
        }}
        onDrop={(e) => {
          console.log('Dropped files', e.dataTransfer.files);
        }}
      >
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">点击或拖拽文件进行上传</p>
        <p className="ant-upload-hint">仅支持压缩包</p>
      </Dragger>
    </Modal>
  );
};

export default UploadModal;
